import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:go_router/go_router.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/options_item.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/theme/app_theme.dart';
import '../../../../common/constants/app_constants.dart';
import '../../../../common/model/base_resp.dart';
import '../../../../provider/global_provider.dart';
import '../../../../router/router_manager.dart';
import '../../../../utils/toast_utils.dart';
import '../../record_history/model/device_details_resp.dart';

const _hour = 60 * 60;

/// 工作模式弹窗
class WorkModeDialog implements CommandDialogInterface {
  final GlobalKey<ScaffoldState> scaffoldKey;
  final String? cmdCode;
  final String? imei;
  final DeviceDetails? deviceDetails;

  late StateSetter _newSetState;

  // 回调函数
  final Function(String cmdContent)? onConfirm;
  final Function(int switchValue)? onchooseModeConfirm;

  WorkModeDialog({
    required this.scaffoldKey,
    required this.cmdCode,
    required this.imei,
    this.deviceDetails,
    this.onConfirm,
    this.onchooseModeConfirm,

  });

  // 模式
  int switchValue = 0;

  // 默认改成30秒
  int modeOptionsIndex1 = 0;

  final modeOptions1 = [
    // 干掉10秒的选项
    // OptionsItem(label: '10秒', value: 10),
    OptionsItem(label: '30秒', value: 30),
    OptionsItem(label: '3分', value: 3 * 60),
    OptionsItem(label: '5分', value: 5 * 60),
  ];

  int modeOptionsIndex2 = 0;

  final modeOptions2 = [
    OptionsItem(label: '1小时', value: 1 * _hour),
    OptionsItem(label: '2小时', value: 2 * _hour),
    OptionsItem(label: '6小时', value: 6 * _hour),
    OptionsItem(label: '12小时', value: 12 * _hour),
    OptionsItem(label: '24小时', value: 24 * _hour),
  ];

  @override
  void show(BuildContext context) {

    return Dialogs.bottomMaterialDialog(
        context: context,
        isScrollControlled: true,
        customView: StatefulBuilder(builder: (newContext, newSetState) {
          _newSetState = newSetState;
          return Container(
            padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '定位模式',
                  style: TextStyle(
                    fontSize: 18,
                    color: AppTheme.themeConfig.primaryTextColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                Row(
                  children: [
                    Expanded(
                      child:
                         deviceDetails?.positionVip == 1
                             ?
                         Text(
                           '秒定模式（已购买）',
                           style: TextStyle(
                             fontSize: 18,
                             color: AppTheme.themeConfig.primaryColor,
                             fontWeight: FontWeight.bold,
                           ),
                         )
                             :
                         Text(
                           '秒定模式（未开通）',
                           style: TextStyle(
                             fontSize: 18,
                             color: AppTheme.themeConfig.primaryTextColor,
                             fontWeight: FontWeight.bold,
                           ),
                         ),
                    ),
                    Radio(
                      value: 3,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        if (deviceDetails?.positionVip != 1) {

                          /// 自定义一个弹窗
                          showGeneralDialog(
                            context: context,
                            pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

                              return Dialog(
                                child: Container(
                                  height: 200,
                                  width: 300,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(16),
                                      color: AppTheme.themeConfig.greyBgColor
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      const SizedBox(height: 1),
                                      const Text(
                                        '您还没开通秒定模式',
                                        style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                      const SizedBox(height: 10),
                                      SizedBox(
                                        width: 220, // 设置按钮宽度
                                        height: 40, // 设置按钮高度
                                        child: TextButton(
                                          style: TextButton.styleFrom(
                                            minimumSize: const Size(100, 40),
                                            backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                                            foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                                            textStyle: const TextStyle(
                                              fontSize: 16,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          onPressed: () {
                                            context.push('${RouterManager.vipService}?chooseTabIndex=3').then((value){
                                              Navigator.of(context).pop();
                                            });
                                            Navigator.of(context).pop();
                                          },
                                          child: const Text('前往开通'),
                                        ),
                                      ),

                                      SizedBox(
                                        width: 220, // 设置按钮宽度
                                        height: 40, // 设置按钮高度
                                        child: TextButton(
                                          style: TextButton.styleFrom(
                                            minimumSize: const Size(100, 40),
                                            backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                                            foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                                            textStyle: const TextStyle(
                                              fontSize: 16,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          onPressed: () {
                                            Navigator.of(context).pop();
                                          },
                                          child: const Text('取消'),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                          );
                        }else {
                          newSetState(() {
                            switchValue = value!;
                          });
                        }
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '每10秒上报定位数据，并开启拐点补偿，数据上报频率更高，耗电量增加，可查询轨迹数据更完整，轨迹更完美。',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                // 分割线
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Color(0xffe5e5e5),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '智能模式',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Radio(
                      value: 0,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        newSetState(() {
                          switchValue = value!;
                        });
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '根据定位间隔更新定位，间隔越长越省电，间隔越短历史轨迹精确度越高。',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  children: [
                    Text(
                      '定位间隔: ',
                      style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryTextColor),
                    ),
                    GestureDetector(
                        onTap: () {
                          // 显示picker
                          Picker picker = Picker(
                            adapter: PickerDataAdapter(
                              data: modeOptions1.map((e) => PickerItem(text: Text(e.label), value: e.value)).toList(),
                            ),
                            changeToFirst: true,
                            cancelText: '取消',
                            confirmText: '确定',
                            cancelTextStyle: const TextStyle(color: Colors.grey, fontSize: 16),
                            textAlign: TextAlign.left,
                            textStyle: const TextStyle(color: Colors.black, fontSize: 18),
                            selectedTextStyle: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 18),
                            columnPadding: const EdgeInsets.all(8.0),
                            onConfirm: (Picker picker, List value) {
                              XLogger.info('value: ${value}');
                              XLogger.info('picker.getSelectedValues(): ${picker.getSelectedValues()}');
                              newSetState(() {
                                modeOptionsIndex1 = value[0];
                              });
                            },
                          );
                          picker.selecteds = [modeOptionsIndex1];
                          picker.showModal(context);
                        },
                        child: Text(
                          '${modeOptions1[modeOptionsIndex1].label}',
                          style: TextStyle(fontSize: 16, color: AppTheme.themeConfig.primaryColor),
                        )),
                  ],
                ),
                // 分割线
                // const Divider(
                //   height: 20,
                //   thickness: 1,
                //   color: Color(0xffe5e5e5),
                // ),
                // Row(
                //   children: [
                //     Expanded(
                //       child: Text(
                //         '省电模式',
                //         style: TextStyle(
                //           fontSize: 18,
                //           color: AppTheme.themeConfig.primaryTextColor,
                //           fontWeight: FontWeight.bold,
                //         ),
                //       ),
                //     ),
                //     // 单选框
                //     Radio(
                //       value: 1,
                //       groupValue: switchValue,
                //       onChanged: (value) {
                //         XLogger.info('value: $value');
                //         newSetState(() {
                //           switchValue = value!;
                //         });
                //       },
                //       activeColor: AppTheme.themeConfig.primaryColor,
                //     ),
                //   ],
                // ),
                // Row(
                //   children: [
                //     // 提示语
                //     Expanded(
                //       child: Text(
                //         '每1小时自动更新位置，续航时间长，会影响历史轨迹的精确度。',
                //         style: TextStyle(
                //           fontSize: 16,
                //           color: AppTheme.themeConfig.infoTextColor,
                //         ),
                //       ),
                //     ),
                //   ],
                // ),
                // 分割线
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Color(0xffe5e5e5),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '关闭定位模式',
                        style: TextStyle(
                          fontSize: 18,
                          color: AppTheme.themeConfig.primaryTextColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Radio(
                      value: 2,
                      groupValue: switchValue,
                      onChanged: (value) {
                        XLogger.info('value: $value');
                        newSetState(() {
                          switchValue = value!;
                        });
                      },
                      activeColor: AppTheme.themeConfig.primaryColor,
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 提示语
                    Expanded(
                      child: Text(
                        '关闭定位模式后不能定位，没有轨迹，可提高拾音续航时间。',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          );
        }),
        customViewPosition: CustomViewPosition.BEFORE_TITLE,
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text(
              '取消',
              style: TextStyle(color: Colors.grey, fontSize: 15),
            ),
          ),
          TextButton(
            onPressed: () {
              // 发送指令
              // Navigator.pop(context);
              // if (switchValue == 0 || switchValue == 1) {
              //   _kaiji();
              // }
              onchooseModeConfirm?.call(switchValue);
              onConfirm?.call(getCommand());
            },
            child: Text(
              '发送指令',
              style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontSize: 15),
            ),
          ),
        ]);
  }

  @override
  String getCommand() {
    // 拼接指令内容
    if (switchValue == 0) {
      // 智能模式
      return '${cmdCode},${switchValue},${modeOptions1[modeOptionsIndex1].value}';
    }else if (switchValue == 1) {
      // 省电模式
      return '${cmdCode},${switchValue},${_hour}';
    }else if (switchValue == 2) {
      // 关闭定位模式
      return 'nmset,1,0';
    }else {
      return 'nmset,0,10';
    }

  }



  _kaiji() async{  // 开机
    final postData = {
      'imei': imei,
      'content': 'Offline,0',
      'cmdCode': 'Offline',
    };
     final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) async {
        // ToastUtils.dismissLoading();
        if (resp.code == 200) {
          // XLogger.info('获取用户指令配置失败: msg: $resp');

          // ToastUtils.showToast('发送成功');
        } else {

        }
      }, failure: (String msg, int code) {

        XLogger.error('发送指令失败: msg: $msg, code: $code');
      });
    }


  @override
  void updateCmdContent(String cmdContent) {
    XLogger.error(cmdContent);

    if (cmdContent.isEmpty) {
      return;
    }
    //从远程页面跳进来的，由于之前拼了一个  接口2 的状态
    final cmdContentList = cmdContent.split(',');
    if (cmdContentList.length > 3) {
      XLogger.info(cmdContentList);
      XLogger.info(cmdContentList[3]);
      if (cmdContentList[3] == "null") {
        switchValue = int.parse(cmdContentList[1]);
      }else {
        switchValue = int.parse(cmdContentList[3]);
        //如果接口1 和接口2 模式状态不一样，取设备模式
        if (cmdContent == "nmset,1,0,${cmdContentList[3]}") {
          switchValue = 2;
        }else
        if (int.parse(cmdContentList[3]) != int.parse(cmdContentList[1]) && int.parse(cmdContentList[3]) == 0) {
          switchValue = int.parse(cmdContentList[1]);
        }
        XLogger.info(switchValue);
        if (switchValue == 3 && deviceDetails?.positionStatus == 0) {
          switchValue = 0;
        }

      }
    }else { // 就算为空时也是
      XLogger.info(cmdContentList);
      if (cmdContentList[1] == "null") {
        switchValue = 0;
      }else {
        switchValue = int.parse(cmdContentList[1]);
      }
      return;
    }
    XLogger.info(switchValue);
    if (switchValue == 0) {
      // 智能模式
      var index = modeOptions1.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
      if (index == -1) {
      }else{
        modeOptionsIndex1 = index;
      }
    } else if (switchValue == 1){
      // 省电模式
      var index = modeOptions2.indexWhere((element) => element.value == int.parse(cmdContentList[2]));
      if (index != -1) {
      }else {
        modeOptionsIndex2 = index;
      }
    }
  }

}
